import logging

from django.core.exceptions import ValidationError
from django.http import JsonResponse
from django.views import View
import json

from drf_spectacular.utils import OpenApiExample, extend_schema
from rest_framework.response import Response
from rest_framework.views import APIView

from app.services.merchant_service import MerchantService
from middleware.util import AUTH_HEADER_PARAM

logger = logging.getLogger('app')

@extend_schema(
    tags=['商家模块'],
    summary='商家注册',
    description='普通用户申请成为商家，填写基础信息并上传图片',
    request={
        'application/json': {
            'type': 'object',
            'properties': {
                'user_id': {'type': 'string', 'format': 'uuid'},
                'shop_name': {'type': 'string'},
                'location': {'type': 'string'},
                'contact_info': {'type': 'string'},
                'business_hours': {'type': 'string'},
                'introduction': {'type': 'string', 'nullable': True},
                'images': {
                    'type': 'array',
                    'items': {'type': 'string'},  # 可替换为 base64 或 image_id
                    'description': '图片数据列表'
                }
            },
            'required': ['user_id', 'shop_name', 'location', 'contact_info', 'business_hours']
        }
    },
    responses={
        201: {
            'description': '注册成功',
            'type': 'object',
            'properties': {
                'code': {'type': 'integer'},
                'message': {'type': 'string'},
                'data': {
                    'type': 'object',
                    'properties': {
                        'merchant_id': {'type': 'string', 'format': 'uuid'},
                        'shop_name': {'type': 'string'}
                    }
                }
            }
        },
        400: {'description': '参数错误或商家名已被占用'},
        403: {'description': '用户不是普通用户'}
    },
    examples=[
        OpenApiExample(
            name='注册成功示例',
            value={
                'code': 201,
                'message': '商家注册成功',
                'data': {
                    'merchant_id': 'abc123e4-5678-90ef-ghij-klmnopqrstuv',
                    'shop_name': '我的小店'
                }
            },
            response_only=True
        )
    ]
)
class RegisterMerchantView(APIView):
    def post(self, request):
        print("Raw request body:", request.body.decode('utf-8'))
        try:

            data = request.data
            user_id = data.get('user_id')
            shop_name = data.get('shop_name')
            location = data.get('location')
            contact_info = data.get('contact_info')
            business_hours = data.get('business_hours')
            images = data.get('images', [])
            introduction = data.get('introduction')

            result = MerchantService.register_merchant(
                user_id=user_id,
                shop_name=shop_name,
                location=location,
                contact_info=contact_info,
                business_hours=business_hours,
                images=images,
                introduction=introduction
            )
            return result

        except ValidationError as e:
            logger.error(f"请求处理失败: {str(e)}", exc_info=True)
            return Response({"code": 400, "message": str(e)}, status=400)
        except Exception as e:
            logger.error(f"请求处理失败: {str(e)}", exc_info=True)
            return Response({
                "code": 500,
                "message": "系统错误，请稍后再试"
            }, status=500)
@extend_schema(
    tags=['商家模块'],
    summary='更新商家图片',
    description='商家更新其店铺图片（支持多张图片上传）',
    parameters=[AUTH_HEADER_PARAM],
    request={
        'application/json': {
            'type': 'object',
            'properties': {
                'images': {
                    'type': 'array',
                    'items': {'type': 'string'},
                    'description': '图片数据列表'
                }
            },
            'required': ['images']
        }
    },
    responses={
        200: {
            'description': '更新成功',
            'type': 'object',
            'properties': {
                'code': {'type': 'integer'},
                'message': {'type': 'string'},
                'data': {
                    'type': 'object',
                    'properties': {
                        'merchant_id': {'type': 'string', 'format': 'uuid'},
                        'image_count': {'type': 'integer'}
                    }
                }
            }
        },
        400: {'description': '图片上传失败或商家不存在'},
        403: {'description': '权限不足'}
    }
)
class UpdateMerchantImagesView(APIView):
    def put(self, request):
        try:
            user_id = getattr(request, 'user_id', None)
            role = getattr(request, 'role', None)
            if not user_id or role != 'merchant':
                return Response({"code": 403, "message": "权限不足"}, status=403)

            data = request.data
            images = data.get('images', [])
            result = MerchantService.update_merchant_images(user_id, images)
            return result

        except ValidationError as e:
            return Response({"code": 400, "message": str(e)}, status=400)
        except Exception as e:
            return Response({"code": 500, "message": f"系统错误：{str(e)}"}, status=500)



@extend_schema(
    tags=['商家模块'],
    summary='获取商家详细信息',
    description='根据商家 ID 获取完整信息（含图片）',
    responses={
        200: {
            'description': '成功',
            'type': 'object',
            'properties': {
                'code': {'type': 'integer'},
                'message': {'type': 'string'},
                'data': {
                    'type': 'object',
                    'properties': {
                        'merchant_id': {'type': 'string', 'format': 'uuid'},
                        'shop_name': {'type': 'string'},
                        'location': {'type': 'string'},
                        'contact_info': {'type': 'string'},
                        'business_hours': {'type': 'string'},
                        'introduction': {'type': 'string', 'nullable': True},
                        'register_time': {'type': 'string', 'format': 'date-time'},
                        'images': {
                            'type': 'array',
                            'items': {
                                'type': 'object',
                                'properties': {
                                    'image_id': {'type': 'string', 'format': 'uuid'},
                                    'mime_type': {'type': 'string'},
                                    'is_cover': {'type': 'boolean'},
                                    'sort_order': {'type': 'integer'}
                                }
                            }
                        }
                    }
                }
            }
        },
        404: {'description': '商家不存在'}
    }
)
class GetMerchantInfoView(APIView):
    def get(self, request, merchant_id):
        try:
            response = MerchantService.get_merchant_info(merchant_id)
            return response
        except Exception as e:
            return Response({"code": 500, "message": f"系统错误：{str(e)}"}, status=500)


@extend_schema(
    tags=['商家模块'],
    summary='更新商家基本信息',
    description='商家更新自己的店铺信息（如名称、地址、营业时间等）',
    parameters=[AUTH_HEADER_PARAM],
    request={
        'application/json': {
            'type': 'object',
            'properties': {
                'shop_name': {'type': 'string'},
                'location': {'type': 'string'},
                'contact_info': {'type': 'string'},
                'business_hours': {'type': 'string'},
                'introduction': {'type': 'string', 'nullable': True}
            }
        }
    },
    responses={
        200: {
            'description': '更新成功',
            'type': 'object',
            'properties': {
                'code': {'type': 'integer'},
                'message': {'type': 'string'},
                'data': {
                    'type': 'object',
                    'properties': {
                        'merchant_id': {'type': 'string', 'format': 'uuid'},
                        'shop_name': {'type': 'string'},
                        'location': {'type': 'string'},
                        'introduction': {'type': 'string', 'nullable': True}
                    }
                }
            }
        },
        400: {'description': '参数错误或商家不存在'},
        403: {'description': '权限不足'}
    }
)
class UpdateMerchantInfoView(APIView):
    def put(self, request):
        try:
            user_id = getattr(request, 'user_id', None)
            role = getattr(request, 'role', None)
            if not user_id or role != 'merchant':
                return Response({"code": 403, "message": "权限不足"}, status=403)

            data = request.data
            result = MerchantService.update_merchant_info(
                user_id=user_id,
                shop_name=data.get("shop_name"),
                location=data.get("location"),
                contact_info=data.get("contact_info"),
                business_hours=data.get("business_hours"),
                introduction=data.get("introduction"),
                datetime = data.get("create_time")
            )
            return result

        except ValidationError as e:
            return Response({"code": 400, "message": str(e)}, status=400)
        except Exception as e:
            logger.error(f"请求处理失败: {str(e)}", exc_info=True)
            return Response({"code": 500, "message": f"系统错误：{str(e)}"}, status=500)

@extend_schema(
    tags=['商家模块'],
    summary='获取所有商家列表',
    description='返回所有注册的商家及其简要信息（用于首页展示）',
    responses={
        200: {
            'description': '成功',
            'type': 'object',
            'properties': {
                'code': {'type': 'integer'},
                'message': {'type': 'string'},
                'data': {
                    'type': 'array',
                    'items': {
                        'type': 'object',
                        'properties': {
                            'merchant_id': {'type': 'string', 'format': 'uuid'},
                            'shop_name': {'type': 'string'},
                            'location': {'type': 'string'},
                            'contact_info': {'type': 'string'},
                            'business_hours': {'type': 'string'},
                            'introduction': {'type': 'string', 'nullable': True},
                            'category_count': {'type': 'integer'},
                            'recent_order_count': {'type': 'integer'},
                            'avg_rating': {'type': 'number', 'nullable': True},
                            'cover_image': {
                                'type': 'object',
                                'properties': {
                                    'data': {'type': 'string'},
                                    'mime_type': {'type': 'string'}
                                }
                            }
                        }
                    }
                }
            }
        }
    }
)
class ListAllMerchantsView(APIView):
    def get(self, request):
        try:
            response = MerchantService.list_all_merchants()
            return response
        except Exception as e:
            return Response({"code": 500, "message": f"系统错误：{str(e)}"}, status=500)